package com.fubowen.lepton.engine.impl

import com.fubowen.lepton.engine.ISearchEngine
import com.fubowen.lepton.ui.search.recycler.Search
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import org.jsoup.Jsoup

class ShenSearchEngine : ISearchEngine {

    private var _page: Int = 0
    private var _pageSize: Int = 0
    private var _keyword: String = ""
    private var _currentIndex = 0

    override val isEnable: Boolean = false

    override fun getUrl(keyword: String?): String? {
        if (keyword.isNullOrBlank()) {
            return null
        }
        if (keyword != _keyword) {
            _page = 0
            _pageSize = 0
        }
        _keyword = keyword
        return "https://quark.sm.cn/s?q=$_keyword&safe=1&snum=0&by=next&med_theme=&layout=html&page=$_page"
    }

    override fun getSearchResultFlow(keyword: String?) = flow {
        val url = getUrl(keyword)
        if (!url.isNullOrBlank()) {
            val document = Jsoup.connect(url).userAgent("Android").get()
            runBlocking {
                val list = document.getElementsByClass("sc_structure_web_novel")
                val aboutList = document.getElementsByClass("sc_text_recommend")
                list.forEach {
                    val title = it.getElementsByClass("c-header-inner")
                    val content = it.getElementsByClass("c-media-content")
                    var type = content[0]
                    var description = content[1]
                    val search = Search()
                    search.id = _currentIndex
                    search.title = title?.text()
                    search.description = content?.text()
                    search.titleHtml = title.outerHtml()
                    search.descriptionHtml = content?.outerHtml()
                    search.url = title?.attr("href")
                    _currentIndex++
                    emit(search)
                }
            }
        }
    }
}